import tkinter as tk
from tkinter import ttk
import win32gui
import win32con
from pynput import mouse
import threading


class RightClickWindowCapture:
    def __init__(self):
        self.status_label = None
        self.btn_toggle = None
        self.root = tk.Tk()
        self.root.title("右键捕获工具 - 未启动")
        self.root.geometry("680x450")

        # 获取窗口自身位置信息
        self.window_rect = self.get_window_rect()
        # 创建主容器
        self.main_frame = tk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        # 初始化列表组件
        self.create_list_widget()
        # 添加操作按钮
        self.create_control_buttons()

        # 状态管理
        self.capturing = False
        self.listener = None
        self.handles = set()

    def create_control_buttons(self):
        # 按钮容器
        btn_frame = tk.Frame(self.main_frame)
        btn_frame.pack(fill=tk.X, pady=5)

        # 添加按钮
        self.btn_toggle = tk.Button(btn_frame, text="开始捕获", command=self.toggle_capture)
        self.btn_toggle.pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="删除选中", command=self.delete_selected).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="清空列表", command=self.clear_list).pack(side=tk.LEFT, padx=5)
        self.status_label = ttk.Label(self.root, text="捕获状态：停止中")
        self.status_label.pack(side=tk.RIGHT, padx=5)

    def create_list_widget(self):
        # 创建带滚动条的Treeview
        self.tree_frame = tk.Frame(self.main_frame)
        self.tree_frame.pack(fill=tk.BOTH, expand=True)
        self.tree_frame.config(width=320)  # 覆盖为固定像素宽度
        # 垂直滚动条
        self.v_scroll = ttk.Scrollbar(self.tree_frame, orient=tk.VERTICAL)

        # 配置列表列
        self.tree = ttk.Treeview(
            self.tree_frame,
            columns=("hwnd", "title", "remark"),
            yscrollcommand=self.v_scroll.set,
            selectmode="browse"  # 可改为 extended 支持多选
        )

        # 配置滚动条
        self.v_scroll.config(command=self.tree.yview)

        # 布局组件
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        self.v_scroll.pack(side=tk.RIGHT, fill=tk.Y)

        # 配置列参数
        self.tree.column("#0", width=0, stretch=tk.NO)  # 隐藏首列
        self.tree.heading("hwnd", text="姓名", anchor=tk.W)
        self.tree.heading("title", text="年龄", anchor=tk.CENTER)
        self.tree.heading("remark", text="性别", anchor=tk.CENTER)

        # 设置列宽
        self.tree.column("hwnd", width=80, minwidth=100, stretch=False)
        self.tree.column("title", width=100, anchor=tk.CENTER, stretch=False)
        self.tree.column("remark", width=180, anchor=tk.CENTER, stretch=False)

    def get_window_rect(self):
        """获取当前窗口的屏幕坐标"""
        hwnd = win32gui.GetForegroundWindow()
        return win32gui.GetWindowRect(hwnd)

    def is_in_self_window(self, x, y):
        """判断坐标是否在程序窗口范围内"""
        left, top, right, bottom = self.window_rect
        return left <= x <= right and top <= y <= bottom

    def on_click(self, x, y, button, pressed):
        """右键点击事件处理（带区域过滤）"""
        if button == mouse.Button.right and pressed and self.capturing:
            if self.is_in_self_window(x, y):
                return  # 忽略自身窗口区域

            hwnd = win32gui.WindowFromPoint((x, y))
            if hwnd not in self.handles:
                info = self.get_window_info(hwnd)
                if info:
                    # 示例添加新记录
                    self.tree.insert("", tk.END, values=info)
                    self.tree.see(self.tree.get_children()[-1])  # 滚动到新项

    def delete_selected(self):
        selected_items = self.tree.selection()
        for item in selected_items:
            self.tree.delete(item)

    def clear_list(self):
        for item in self.tree.get_children():
            self.tree.delete(item)

    def toggle_capture(self):
        """切换捕获状态（即时响应）"""
        self.capturing = not self.capturing
        self.window_rect = self.get_window_rect()  # 刷新窗口位置

        if self.capturing:
            self.btn_toggle.config(text="停止捕获")
            self.status_label.config(text="状态：捕获中")
            self.start_listener()
        else:
            self.btn_toggle.config(text="开始捕获")
            self.status_label.config(text="状态：已停止")
            self.stop_listener()

    def start_listener(self):
        """启动监听线程"""
        self.listener = mouse.Listener(on_click=self.on_click)
        self.listener_thread = threading.Thread(target=self.listener.start)
        self.listener_thread.daemon = True
        self.listener_thread.start()

    def stop_listener(self):
        """安全停止监听"""
        if self.listener:
            self.listener.stop()
            self.listener = None

    def get_window_info(self, hwnd):
        """获取窗口详细信息"""
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            return hwnd, title[:30], "自行备注用于区分是那个角色"
        return None


if __name__ == "__main__":
    app = RightClickWindowCapture()
    app.root.mainloop()
